package com.lagou.java.mission1;

import lombok.*;

import java.sql.*;

public class JDBC_Analysis {

    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        User user = new User();
        try {
            //jdbc:mysql://localhost:3306/databaseName?useUnicode=true&characterEncoding=UTF-8&useOldAliasMetadataBehavior=true&autoReconnect=true&serverTimezone=UTC
            //加载数据库驱动
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?charactorEncoding=utf-8&serverTimezone=UTC", "root", "123456");
            //定义sql语句, ?表示占位符
            String sql = "select * from user where name = ?";
            //获取预处理statement
            preparedStatement = connection.prepareStatement(sql);
            //设置参数, 第一个参数为sql语句中参数的序号(从1开始), 第二个参数为设置的参数值
            preparedStatement.setString(1, "tom");
            //向数据库发出骚起来执行查询, 查询出结果集
            resultSet = preparedStatement.executeQuery();
            //遍历查询结果集
            while(resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                //封装User
                user.setId(id);
                user.setName(name);
            }
            System.out.println(user);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
        }
    }
}

@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
@ToString
class User {
    private String name;
    private int id;
}